package me.seu.demo.test;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 在sftp 上传 .zip文件
 *
 *
 * @since 2020/10/19 18:33
 */
@Slf4j
public class ZipSftp {

    public static void main(String[] args) {
        String fileName = "/Users/liangfeihu/projects/gitee/myown/learning-demo/docs/test.zip";

        File temp = new File(fileName);

        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(temp))) {
            try {
                zos.putNextEntry(new ZipEntry("123.xml"));
                InputStream is = new ByteArrayInputStream("Hello world xml and zip file!".getBytes());
                try {
                    IOUtils.copy(is, zos);
                } catch (Exception e) {
                    log.error(e.getMessage());
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
                zos.closeEntry();

                zos.putNextEntry(new ZipEntry("Image/text.txt"));
                InputStream isTest = new ByteArrayInputStream("just test".getBytes());
                try {
                    IOUtils.copy(isTest, zos);
                } catch (Exception e) {
                    log.error(e.getMessage());
                } finally {
                    if (isTest != null) {
                        isTest.close();
                    }
                }
                zos.closeEntry();
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }

            //流关闭很重要，不然生成的zip文件有问题
            zos.close();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        System.out.println("------- end --------");
    }

}
